var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var listRouter = require('./routes/list');
var loginRouter = require('./routes/login');
var detailRouter = require('./routes/detail');
var userRouter = require('./routes/user');
var onlineRouter = require('./routes/online');

var app = express();

//跨域
const cors = require('cors')
app.use(cors())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
    extended: false
}));
app.use(cookieParser());
//开放静态资源
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use('/', indexRouter);
app.use('/', listRouter);
app.use('/', loginRouter);
app.use('/', detailRouter);
app.use('/', userRouter);
app.use('/', onlineRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    res.send('404 page')
});

// error handler 逻辑错误 统一数据处理 
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    // 返回结果数据处理
    err.status == 200 ? err.msg = 'OK' : err.status = 5000;
    res.send(err)
});

module.exports = app;